package com.rp.system.corn.init;

import com.rp.system.corn.entity.QuartzJob;
import com.rp.system.corn.enums.JobStatus;
import com.rp.system.corn.mapper.JobMapper;
import com.rp.system.corn.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;

import java.util.List;

//项目启动后立即执行
@Slf4j
public class ApplicationInit implements CommandLineRunner  {


    @Value("${corn.enable}")
    private Boolean enable;

    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private JobService jobService;
    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(String... args) throws Exception {
        loadJobToQuartz();
    }

    private void loadJobToQuartz() throws Exception {
        if (enable) {
            log.info("定时任务已挂载");
            List<QuartzJob> jobs = jobMapper.listJob();
            for(QuartzJob job : jobs) {
                jobService.schedulerJob(job);
                if (JobStatus.PAUSED.getStatus().equals(job.getTriggerState())) {
                    scheduler.pauseJob(new JobKey(job.getJobName(), job.getJobGroup()));
                }
            }
        }
    }
}
